package cn.edu.zknu.mita.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * Created by iwlnner on 2020/3/23.
 * 文件上传工具类，待优化
 */
@Component
public class UploadUtils {

    @Value("${upload.url}")
    private String url;
    @Value("${upload.service-url}")
    private String serviceUrl;
    @Autowired
    private ObjectMapper obj;

    public String uploadImage(String dir,MultipartFile imgFile){
        File file=new File(url);
        if(!file.exists()){
            getError(1,"图片保存路径不存在");
        }
        List extList=new ArrayList(){{
            this.add("gif");
            this.add("jpg");
            this.add("jpeg");
            this.add("png");
            this.add("bmp");
        }};
        if("image".equals(dir)){
            String SimpleOriginalName=imgFile.getOriginalFilename();
            String fileExt = SimpleOriginalName.substring(SimpleOriginalName.lastIndexOf(".") + 1).toLowerCase();
            if(!extList.contains(fileExt)){
                return getError(1,"上传图片格式错误");//TODO
            }
            if(imgFile.getSize()>10485760){
                return getError(1,"上传图片大小超过限制");
            }
            String newFileName= UUID.randomUUID().toString()+"."+fileExt;
            //定义图片保存到服务器的地址
            String saveUrl=url+newFileName;
            try{
                Files.copy(imgFile.getInputStream(), Paths.get(saveUrl));
            }catch (Exception e){
                e.printStackTrace();
            }
            //指定KindEditor接收的图片地址
            //return getError(0,saveUrl);
            //模拟服务器
            return getError(0,serviceUrl+newFileName);
        }
        return getError(1,"只能上传图片");
    }

    private String getError(Integer error,String message) {
        String ret="";
        Map<String,Object> successMap=new HashMap<>();
        Map<String,Object> errorMap=new HashMap<>();
        if(0==error){
            successMap.put("error",0);
            successMap.put("url",message);
            try{
                ret=obj.writeValueAsString(successMap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(1==error){
            errorMap.put("error",1);
            errorMap.put("message",message);
            try{
                ret=obj.writeValueAsString(errorMap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ret;
    }
}
